package javase.ch05.homeWork.Demo3;

import java.io.IOException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class TcpService {
   public static void main(String[] args) {
       System.out.println("----------- 我们的世界-Service ------------");
       CopyOnWriteArrayList<Socket> clients = new CopyOnWriteArrayList<>();
       int max = ThreadPoolConfig.corePoolSize + ThreadPoolConfig.maximumPoolSize;
       ServerSocket ss = null;
       //创建线程池
       Threadpool pool = new Threadpool(ThreadPoolConfig.maximumPoolSize, ThreadPoolConfig.corePoolSize);
       try {
           ss = new ServerSocket(10086);

           while (true) {
               Socket socket = ss.accept();
               clients.add(socket);
               System.out.println(socket.getRemoteSocketAddress() + "已上线");
               ServerTasker serverTasker = new ServerTasker(clients, socket, Thread.currentThread());
               pool.execute(serverTasker);

               if(clients.size() == max){
                   ss.close();
                   ss =null;
                   LockSupport.park();
                   try {
                       TimeUnit.SECONDS.sleep(1);
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
                   ss = new ServerSocket(10086);
               }



               // pool.execute(new ReadThread(socket));
               //new Thread(new WriterThread(socket)).start();
           }
       } catch (IOException e) {
           throw new RuntimeException(e);
       } finally {
           if (ss != null) {
               try {
                   ss.close();
               } catch (IOException e) {
                   throw new RuntimeException(e);
               }
           }
       }
   }
}

